﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace WpfApp3
{
    public class XmlHelper
    {

        /// <summary>
        /// Xml列表反序列化
        /// </summary>
        public static T DeserializeMethod<T>(string filePath) where T : class
        {
            var data = default(T);
            if (!File.Exists(filePath))
            {
                return data;
            }
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(filePath);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                data = xs.Deserialize(sr) as T;
                sr.Close();
            }
            catch (Exception)
            { }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
            return data;
        }

        /// <summary>
        ///  Xml列表序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Data"></param>
        public static bool SerializeMethod<T>(string filePath, object Data)
        {
            FileStream fs = null;
            if (string.IsNullOrEmpty(filePath) || Data == null)
            {
                return false;
            }

            try
            {
                if (!File.Exists(filePath))
                {
                    File.Create(filePath);
                }

                fs = new FileStream(filePath, FileMode.Create);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(fs, Data);
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return true;
        }


    }
}
